package com.atstudent.gmall.common.service.impl;/*
 * @author: XueYouPeng
 * @time: 23.9.5 下午 6:08
 */

import com.atstudent.gmall.common.properties.MinioProperties;
import com.atstudent.gmall.common.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;


    @Override
    public String upload(MultipartFile multipartFile) {


        try {
            //创建桶
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build());
            if (!exists){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
            }

            //上传文件
            String uuidFileName = UUID.randomUUID().toString().replace("-", "");
            //获取文件原始名称
            String originalFilename = multipartFile.getOriginalFilename();
            //获取扩展名
            String extension = FilenameUtils.getExtension(originalFilename);
            //真实名称
            String fileName = uuidFileName + "." + extension;
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .build();

            //访问路径 minio的路径+桶的名称+图片名称
            String imageUrl = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + fileName;

            return imageUrl;
        }catch (Exception exception){
            exception.printStackTrace();
            return null;
        }
    }
}
